<template>
  <view class="userinfo-content page_bg_FAFAFA">
    <view class="padd32">
      <button class="mar-top20 userinfo-box" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
        <view class="cr-999 font_s30">
          头像
        </view>
        <view class="flex align-center">
          <image :src="`https://www.worldintek.com:39011/yaolexue-service/${userInfo.icon}`"
            class="w-61 h-61 border-circle mar-right10"></image>
          <u-icon name="arrow-right"></u-icon>
        </view>
      </button>

      <view class="mar-top20 userinfo-box" @click="show = true">
        <view class="cr-999 font_s30">
          昵称
        </view>
        <view class="flex align-center">
          <text class="cr-333 font_s30 mar-right10">{{userInfo.name}}</text>
          <u-icon name="arrow-right"></u-icon>
          <u-modal negativeTop="150" width="280px" :show="show" title="修改昵称" zoom showConfirmButton="true"
            showCancelButton="true" confirmColor="#FA312A" @confirm="confirm" @cancel="cancel">
            <view>
              <u-input border="surround" v-model="nickValue" @change="change"></u-input>
            </view>
          </u-modal>
        </view>

      </view>
      <view class="mar-top20 userinfo-box">
        <view class="cr-999 font_s30">
          电话
        </view>
        <view class="flex align-center">
          <text class="cr-333 font_s30 mar-right10">{{userInfo.phoneNumber}}</text>
          <u-icon name="arrow-right"></u-icon>
        </view>
      </view>
      <view class="mar-top20 userinfo-box">
        <view class="cr-999 font_s30">
          角色
        </view>
        <view class="flex align-center">
          <text class="cr-333 font_s30">{{roleName}}</text>
        </view>
      </view>
      <view class="mar-top20 userinfo-box">
        <view class="cr-999 font_s30">
          单位名称
        </view>
        <view class="flex align-center">
          <text class="cr-333 font_s30">{{userInfo.workUnit}}</text>
        </view>
      </view>
      <view class="mar-top20 userinfo-box">
        <view class="cr-999 font_s30">
          单位地址
        </view>
        <view class="flex align-center">
          <text class="cr-333 font_s30">{{userInfo.location}}</text>
        </view>
      </view>
      <view class="mar-top20 userinfo-box" @click="selectAddress">
        <view class="cr-999 font_s30">
          收货地址
        </view>
        <view class="flex align-center">
          <u-icon name="arrow-right"></u-icon>
        </view>
      </view>
    </view>

    <t-button @handleBtnClick="logout" fontSize="40" content="退出登录" lineWidth="529" lineHeight="88"
      borderRadius="44"></t-button>
  </view>
</template>

<script>
  import userInfoVue from './userInfo.vue';
  export default {
    data() {
      return {
        userInfo: {},
        show: false,
        nickValue: '',
        avatarImg: ''
      };
    },
    onLoad() {
      this.getUserInfo()
      console.log(getApp().globalData.userInfo);
    },
    computed: {
      roleName() {
        const roleId = this.userInfo.roleId;
        switch (roleId) {
          case 3:
            return "门店法人";
          case 4:
            return "企业(质量)负责人";
          case 5:
            return "营业员/店员";
          case 6:
            return "药企代表";
          case 7:
            return "医生/专家";
          case 8:
            return "政府工作人员";
          default:
            return "未知角色";
        }
      }
    },
    methods: {
      onChooseAvatar(avat) {
        if (avat.detail.errMsg === 'chooseAvatar:fail cancel') {
          console.log('用户取消了选择头像');
        } else {
          const avatarUrl = avat.detail.avatarUrl;

          // 显示上传中的加载指示器
          uni.showLoading({
            title: '上传中...',
            mask: true
          });

          // 上传头像文件
          uni.uploadFile({
            filePath: avatarUrl,
            url: this.$baseUrl + '/yaolexue-service-portal/minio/uploadImg',
            header: {
              Authorization: `Bearer ${uni.getStorageSync('token')}`
            },
            name: 'file',
            success: (e) => {
              uni.hideLoading(); // 隐藏加载指示器

              const imgUrl = JSON.parse(e.data);

              if (imgUrl.code === 200) {
                this.avatarImg = imgUrl.data.compressLink;

                // 更新用户头像
                this.updateUserAvatar();
              } else {
                uni.showToast({
                  title: '上传失败',
                  icon: 'none'
                });
              }
            },
            fail: (error) => {
              uni.hideLoading();
              console.error('头像上传失败:', error);
              uni.showToast({
                title: '上传失败',
                icon: 'none'
              });
            }
          });
        }
      },

      // 更新用户头像
      updateUserAvatar() {
        this.$http.put('/yaolexue-service-portal/sysPortalUser/updatePortalUserIcon', {
            icon: this.avatarImg
          })
          .then(async (res) => {
            if (res.code === 200) {
              uni.showToast({
                title: '修改头像成功',
                icon: 'success'
              });
            } else {
              uni.showToast({
                title: '修改头像失败!',
                icon: 'error'
              });
            }

            await this.getUserInfo();
          })
          .catch((error) => {
            console.error('更新用户图标时发生错误：', error);
            uni.showToast({
              title: '修改头像失败!',
              icon: 'error'
            });
          });
      },

      async getUserInfo() {
        const res = await this.$http.get('/yaolexue-service-portal/sysPortalUser/portalUserInfo', {
          isNeedLoading: false
        })

        this.userInfo = res.data
        this.nickValue = res.data.name

        console.log('getUserInfo', res.data);
        if (res.code !== 200) {
          uni.showToast({
            title: '获取失败',
            icon: 'error'
          })
        }
      },
      async logout() {
        try {

          const logoutRes = await this.$http.delete('/yaolexue-service-portal/sysPortalUser/portalUserLogout');

          if (logoutRes.code === 200) {
            this.sysPortalUserOut()
            uni.showToast({
              title: logoutRes.data,
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: '退出错误',
              icon: 'error',
            });
          }
          // await uni.removeStorageSync('userInfo');
          // await uni.removeStorageSync('goodsInfo');
          
          // const LeaveRes = await this.$http.post('/yaolexue-service-portal/sysPortalUser/sysPortalUserOut')
          // console.log('sysPortalUserOut', LeaveRes);
          uni.reLaunch({
            url: '/pages/login/login'
          });
        } catch (error) {
          console.error('Logout error:', error);
          // 处理错误，可能显示错误提示
        }
      },
      selectAddress() {
        uni.navigateTo({
          url: '/subPages/selectAddress/selectAddress'
        })
      },
      async editNickName() {
        try {
          const res = await this.$http.put('/yaolexue-service-portal/sysPortalUser/updatePortalUserNickname', {
            nickname: this.nickValue,
          });

          if (res.code === 200) {
            uni.showToast({
              title: '昵称修改成功',
              icon: 'success',
            });
            await this.getUserInfo();
          } else {
            uni.showToast({
              title: '昵称修改失败',
              icon: 'error',
            });
          }
        } catch (error) {
          console.error('更新昵称时出错:', error);
          uni.showToast({
            title: '昵称修改失败',
            icon: 'error',
          });
        }
      },
      // 离开系统
     async sysPortalUserOut() {
        try {
          const res = await this.$http.post('/yaolexue-service-portal/sysPortalUser/sysPortalUserOut');
          console.log('离开小程序', res);
          // if(res.code !== 200) {
          //   uni.showToast({
          //     title: '请重新登录!',
          //     icon: 'error'
          //   })
          // }
         
        } catch (error) {
          
          console.error('Error in sysPortalUserIn request:', error);
        }
      },
      change() {

      },
      async confirm() {
        this.show = false

        await this.editNickName()
      },
      cancel() {
        this.show = false
      }
    }
  }
</script>

<style lang="scss" scoped>
  .userinfo-content {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .userinfo-box {
    width: 100%;
    height: 100rpx;
    background: #FFFFFF;
    border-radius: 10rpx;
    padding: 0 21rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    &::after {
      border: 0 !important;
    }
  }


  ::v-deep .btn-content {
    background-color: inherit;
    margin-bottom: 106rpx;

  }
</style>